package org.example.controller;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.example.domain.CarPlan;
import org.example.listener.CarPlanListener;
import org.example.service.CarPlanService;
import org.example.util.Result;
import org.example.util.UploadMinioUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("carPlan")
public class CarPlanController {
    @Autowired
    CarPlanService carPlanService;


    @RequestMapping("carPlanList")
    public Result carPlanList(CarPlan carPlan,@RequestParam(defaultValue = "1") Integer pageNum){
        PageHelper.startPage(pageNum,5);
        List<CarPlan> list =  carPlanService.listAll(carPlan);
        return Result.success(new PageInfo<>(list));
    }

    @RequestMapping("exculOut")
    public void exculOut(CarPlan carPlan, HttpServletResponse response) throws IOException {
        List<CarPlan> carPlans =    carPlanService.listAll(carPlan);

        String simpleName = CarPlan.class.getSimpleName();//文件名称
        //这列需要指定写用哪个class去读，然后写到第一个sheet,
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode(simpleName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), CarPlan.class).sheet("优惠券模块").doWrite(carPlans);
    }


    /**
     * 导入
     * @param file
     * @return
     * @throws IOException
     */
    @RequestMapping("upload")
    public Result upload(MultipartFile file) throws IOException {
        HashMap<String, Object> map = new HashMap<>();
        try {
            map.put("code",200);
            EasyExcel.read(file.getInputStream(),CarPlan.class,new CarPlanListener(carPlanService)).sheet().doRead();
        } catch (IOException e) {
            map.put("code",500);
           e.printStackTrace();
        }
        return Result.success(map);
    }

    @RequestMapping("uploadFile")
    public Result uploadFile(MultipartFile file){
        String s = UploadMinioUtils.uploadPic(file);
        return Result.success(s);
    }

}
